package com.study.mirrorforest.main.model.auth.service.impl;

import com.google.code.kaptcha.Producer;
import com.study.mirrorforest.main.common.response.R;
import com.study.mirrorforest.main.model.auth.dto.CaptchaVO;
import com.study.mirrorforest.main.model.auth.dto.VerifyCaptchaDTO;
import com.study.mirrorforest.main.model.auth.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private Producer kaptchaProducer;

    // 临时存储验证码，实际项目中应使用 Redis
    private final Map<String, String> captchaStore = new ConcurrentHashMap<>();
    private static final long CAPTCHA_EXPIRE_TIME = 5 * 60 * 1000; // 5分钟过期

    @Override
    public R<CaptchaVO> generateCaptcha() {
        try {
            // 生成验证码文本
            String captchaText = kaptchaProducer.createText();
            System.out.println("[CaptchaService] 生成的验证码: " + captchaText);

            // 生成唯一ID
            String captchaId = UUID.randomUUID().toString();

            // 存储验证码（实际项目中应使用 Redis 并设置过期时间）
            captchaStore.put(captchaId, captchaText.toLowerCase());

            // 生成验证码图片
            BufferedImage image = kaptchaProducer.createImage(captchaText);

            // 将图片转换为 Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64Image = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(imageBytes);

            CaptchaVO captchaVO = new CaptchaVO(captchaId, base64Image);
            return R.ok(200, "验证码生成成功", captchaVO);
        } catch (IOException e) {
            System.err.println("[CaptchaService] 验证码生成失败: " + e.getMessage());
            return R.error(500, "验证码生成失败");
        }
    }

    @Override
    public R<String> verifyCaptcha(VerifyCaptchaDTO verifyCaptchaDTO) {
        String captchaId = verifyCaptchaDTO.getCaptchaId();
        String captchaCode = verifyCaptchaDTO.getCaptchaCode();

        if (captchaId == null || captchaCode == null) {
            return R.error(400, "验证码ID或验证码不能为空");
        }

        String storedCaptcha = captchaStore.get(captchaId);
        if (storedCaptcha == null) {
            return R.error(400, "验证码已过期或不存在");
        }

        // 验证完后删除验证码
        captchaStore.remove(captchaId);

        if (!storedCaptcha.equalsIgnoreCase(captchaCode)) {
            return R.error(400, "验证码错误");
        }

        return R.ok(200, "验证码验证成功");
    }
}

